﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Conditions;
using System.Data.SqlClient;
using System.Data;

public partial class Admin_Chitiethoadon : System.Web.UI.Page
{
    SqlConnection sqlconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    private void HienThiTinhTrang(string tinhtrang)
    {
        switch (tinhtrang)
        {
            case "0":
                lttinhtrang.Text = "Chưa giao hàng";
                break;
            case "1":
                lttinhtrang.Text = "Đã giao hàng";
                btnluu.Visible = false;
                drdhinhthucthanhtoan.Enabled = false;
                drdhinhthucgiaohang.Enabled = false;
                ViewState["tinhtrang"] = 1;
                ckdagiaohang.Checked = true;
                ckdagiaohang.Enabled = false;
                btnhuy.Visible = false;
                break;
            case "-1":
                lttinhtrang.Text = "Đã hủy";
                btnluu.Visible = false;
                drdhinhthucthanhtoan.Enabled = false;
                drdhinhthucgiaohang.Enabled = false;
                ViewState["tinhtrang"] = -1;
                btnhuy.Visible = false; 
                break;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["tendangnhap"] == null || Session["tendangnhap"].ToString().Equals(""))
        {
            string url = Server.UrlEncode(Request.RawUrl);
            Response.Redirect("~/Admin/Login.aspx?ReturnUrl=" + url);
        }
        if (IsPostBack == false)
        {
            string sqlquery = @"select hd.*,kh.tenkhachhang from hoadon hd 
                                inner join khachhang kh on hd.makh=kh.id_row
                                where hd.id_hoadon = " + Request.QueryString["id"].ToString();
            SqlDataAdapter da = new SqlDataAdapter(sqlquery, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            ViewState["tinhtrang"] = 0;
            if (dt.Rows.Count > 0)
            {
                ltkhachhang.Text = dt.Rows[0]["tenkhachhang"].ToString();
                ltmahoadon.Text = dt.Rows[0]["mahd"].ToString();
                ltngay.Text = string.Format("{0:dd/MM/yyyy}", dt.Rows[0]["ngaylap"]);
                lttongtien.Text = string.Format("{0:###,###}", dt.Rows[0]["tongtien"]);
                drdhinhthucgiaohang.Text = dt.Rows[0]["hinhthucgiaohang"].ToString();
                drdhinhthucthanhtoan.Text = dt.Rows[0]["hinhthucthanhtoan"].ToString();
                HienThiTinhTrang(dt.Rows[0]["tinhtrang"].ToString());
            }
        }
    }

    protected void txtsoluong_TextChanged(object sender, EventArgs e)
    {
        if (ViewState["tinhtrang"].ToString().Equals("0") == true)
        {
            TextBox txt = (TextBox)sender;
            int sl = 0;
            if (!int.TryParse(txt.Text.Replace(",", ""), out sl))
            {
                MessengeBox.Show(this, "Vui lòng nhập số lượng sản phẩm");
                txt.Focus();
                return;
            }
            if (sl == 0)
            {
                MessengeBox.Show(this, "Vui lòng nhập số lượng sản phẩm lớn hơn 0");
                txt.Focus();
                return;
            }
            Label lblDonGia = (Label)txt.Parent.Parent.FindControl("lbdongia");
            Label lblTongTien = (Label)txt.Parent.Parent.FindControl("lbthanhtien");
            decimal dongia = int.Parse(lblDonGia.Text.Replace(",", "").Replace(".", ""));
            lblTongTien.Text = string.Format("{0:###,###}", sl * dongia);
        }
    }

    protected void btnhuy_Click(object sender, EventArgs e)
    {
        string sqlquery = @"update hoadon
                            set tinhtrang = @tinhtrang
                            where id_hoadon = @id_hoadon";
        SqlCommand sqlcom = new SqlCommand(sqlquery, sqlconn);
        sqlcom.Parameters.AddWithValue("@tinhtrang", -1);
        sqlcom.Parameters.AddWithValue("@id_hoadon", Request.QueryString["id"]);
        try
        {
            sqlconn.Open();
            if (sqlcom.ExecuteNonQuery() > 0)
            {
                MessengeBox.Show(this, "Hủy đơn hàng thành công");
                HienThiTinhTrang("-1");
            }
            else
            {
                MessengeBox.Show(this, "Hủy đơn hàng không thành công");
            }
        }
        catch (Exception ex)
        {
            MessengeBox.Show(this, "Lỗi :" + ex.Message);
        }
        finally
        {
            sqlconn.Close();
        }
    }

    protected void btnluu_Click(object sender, EventArgs e)
    {
        string sqlquery = @"update hoadon
                            set hinhthucthanhtoan = @hinhthucthanhtoan,
                            hinhthucgiaohang = @hinhthucgiaohang,
                            tinhtrang = @tinhtrang
                            where id_hoadon = @id_hoadon";
        SqlCommand sqlcom = new SqlCommand(sqlquery, sqlconn);
        sqlcom.Parameters.AddWithValue("@hinhthucthanhtoan", drdhinhthucthanhtoan.SelectedValue);
        sqlcom.Parameters.AddWithValue("@hinhthucgiaohang", drdhinhthucgiaohang.SelectedValue);
        sqlcom.Parameters.AddWithValue("@tinhtrang", ckdagiaohang.Checked == true ? 1 : 0);
        sqlcom.Parameters.AddWithValue("@id_hoadon", Request.QueryString["id"]);
        try
        {
            sqlconn.Open();
            if (sqlcom.ExecuteNonQuery() > 0)
            {
                decimal tong = 0;
                foreach (GridViewRow dr in grvds.Rows)
                {
                    TextBox txt = (TextBox)dr.FindControl("txtsoluong");
                    int sl = 1;
                    if (!int.TryParse(txt.Text.Replace(",", ""), out sl))
                    {
                        MessengeBox.Show(this, "Vui lòng nhập số lượng sản phẩm thứ " + (dr.RowIndex + 1).ToString());
                        continue;
                    }
                    if (sl == 0)
                    {
                        sl = 1;
                    }
                    Label lblDonGia = (Label)dr.FindControl("lbdongia");
                    decimal dongia = decimal.Parse(lblDonGia.Text.Replace(",", "").Replace(".", ""));
                    Label lblThanhTien = (Label)dr.FindControl("lbthanhtien");
                    Label lblIdSanPham = (Label)dr.FindControl("lbid_sp");
                    lblThanhTien.Text = string.Format("{0:###,###}", sl * dongia);
                    tong += sl * dongia;

                    sqlquery = @"update chitiethoadon
                                 set soluong = @soluong,
                                 thanhtien = @thanhtien
                                 where id_hd = @id_hd
                                 and id_sp = @id_sp";
                    sqlcom = new SqlCommand(sqlquery, sqlconn);
                    sqlcom.Parameters.AddWithValue("@soluong", sl);
                    sqlcom.Parameters.AddWithValue("@thanhtien", sl * dongia);
                    sqlcom.Parameters.AddWithValue("@id_hd", Request.QueryString["id"]);
                    sqlcom.Parameters.AddWithValue("@id_sp", lblIdSanPham.Text);
                    sqlcom.ExecuteNonQuery();
                }

                sqlquery = @"update hoadon
                            set tongtien = @tongtien
                            where id_hoadon = @id_hoadon";
                sqlcom = new SqlCommand(sqlquery, sqlconn);
                sqlcom.Parameters.AddWithValue("@tongtien", tong);
                sqlcom.Parameters.AddWithValue("@id_hoadon", Request.QueryString["id"]);
                sqlcom.ExecuteNonQuery();
                sqlconn.Close();
                MessengeBox.Show(this, "Cập nhật thành công");
                HienThiTinhTrang(ckdagiaohang.Checked == true ? "1" : "0");
            }
            else
            {
                MessengeBox.Show(this, "Cập nhật không thành công");
            }
        }
        catch (Exception ex)
        {
            MessengeBox.Show(this, "Lỗi :" + ex.Message);
        }
        finally
        {
            sqlconn.Close();
        }
    }
}
